package com.googlecode.milib.tools {
	import com.googlecode.milib.base.MLBroadcastClass;

	/**
	 * @author Marek Brun
	 */
	public class PaginatorModel extends MLBroadcastClass {

		public var event_Changed:String='Changed';
		
		private var _currerntPage : Number;
		private var _totalElements : Number;
		private var _elementsInOnePage : Number;
		private var isSkip : Boolean;
		
		public function PaginatorModel(isSkip:Boolean, totalElements:Number=0, elementsInOnePage:Number=1, initialPage:Number=0) {
			_totalElements=totalElements;
			_elementsInOnePage=elementsInOnePage;
			_currerntPage=initialPage;
			this.isSkip=isSkip;
			
		}
		
		public function getTotalPages():Number {
			return Math.ceil(totalElements/elementsInOnePage);
		}
		
		public function getCurrentPageElementsIndexes():Array {
			var indexes:Array=[];
			for(var i:int=currerntPage*elementsInOnePage;i<totalElements && i<(currerntPage+1)*elementsInOnePage;i++){
				indexes.push(i);
			}
			return indexes;
		}
		
		public function getIsNextAvailable():Boolean {
			return (currerntPage<getTotalPages()-1 || isSkip);
		}
		
		public function getIsPrevAvailable():Boolean {
			return (currerntPage>0 || isSkip);
		}
		
		
		public function get totalElements():Number {
			return _totalElements;
		}
		
		public function set totalElements(num:Number):void { 
			if(num==_totalElements || num<0){ return; }
			_totalElements=num;
			if(!repairPages()){ broadcastEvent(event_Changed); }
		}
		
		
		public function get elementsInOnePage():Number {
			return _elementsInOnePage;
		}
		
		public function set elementsInOnePage(num:Number):void {
			if(num==_elementsInOnePage || num<1){ return; }
			_elementsInOnePage=num;
			if(!repairPages()){ broadcastEvent(event_Changed); }
		}
		
		public function get currerntPage():Number {
			return _currerntPage;
		}
		
		public function set currerntPage(page:Number):void {
			if(currerntPage==page){ return; }
			var newPage:Number=_currerntPage;
			if(page==-1 && isSkip){
				newPage=getTotalPages()-1;
			}else if(page==getTotalPages() && isSkip){
				newPage=0;
			}else if(page>-1 && page<getTotalPages()){
				newPage=page;
			}
			if(newPage!=_currerntPage){
				_currerntPage=newPage;
				broadcastEvent(event_Changed);
			}
		}
		
		private function repairPages():Boolean {
			if(currerntPage>getTotalPages()-1){
				currerntPage=getTotalPages()-1;
				return true;
			} 
			return false;
		}
		
	}
}